package com.zlb.controller;

import com.zlb.domain.User;
import com.zlb.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

  private Logger logger = LoggerFactory.getLogger(LoginController.class);

  @Autowired
  private UserService userService;

  /**
   * 用户名密码登录
   *
   * @return token
   */
  @PostMapping(value = "/login")
  public ResponseEntity<Object> login(@RequestBody User loginInfo) {
    Subject subject = SecurityUtils.getSubject();
    try {
      UsernamePasswordToken token = new UsernamePasswordToken(loginInfo.getUsername(),
          loginInfo.getPassword());
      subject.login(token);
      User user = (User) subject.getPrincipal();
      String newToken = userService.generateJwtToken(user.getUsername());
      return ResponseEntity.ok(newToken);
    } catch (AuthenticationException e) {
      logger.error("User {} login fail, Reason:{}", loginInfo.getUsername(), e.getMessage());
      return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    } catch (Exception e) {
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
  }

  /**
   * 退出登录
   */
  @GetMapping(value = "/logout")
  public ResponseEntity<Void> logout() {
    Subject subject = SecurityUtils.getSubject();
    if (subject.getPrincipals() != null) {
      User user = (User) subject.getPrincipals().getPrimaryPrincipal();
      userService.deleteLoginInfo(user.getUsername());
    }
    SecurityUtils.getSubject().logout();
    return ResponseEntity.ok().build();
  }

}
